package com.sxwl.auth.netty;

import com.sxwl.pojo.User;
import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author reading
 * @Description TODO
 * @Date 2020/4/12 21:37
 */
public class UserChannelMap {
    // 用户保存用户id与通道的Map对象
    private static ConcurrentHashMap<String, Channel> userChannelMap;

    static {
        userChannelMap = new ConcurrentHashMap<>();
    }

    /**
     * 添加用户id与channel的关联
     *
     * @param userid
     * @param channel
     */
    public static void put(String userid, Channel channel) {
        userChannelMap.put(userid, channel);
    }

    /**
     * 根据用户id移除用户id与channel的关联
     *
     * @param userid
     */
    public static void remove(String userid) {
        userChannelMap.remove(userid);
    }

    /**
     * 根据通道id移除用户与channel的关联
     *
     * @param channelId 通道的id
     */
    public static void removeByChannelId(String channelId) {
        if (!StringUtils.isNotBlank(channelId)) {
            return;
        }
        for (String s : userChannelMap.keySet()) {
            Channel channel = userChannelMap.get(s);
            if (channelId.equals(channel.id().asLongText())) {
                System.out.println("客户端连接断开,取消用户" + s + "与通道" + channelId + "的关联");
                userChannelMap.remove(s);
                break;
            }
        }
    }
    /**
     * 根据好友id获取对应的通道
     *
     * @param friendid 好友id
     * @return Netty通道
     */
    public static Channel get(String friendid) {
        return userChannelMap.get(friendid);
    }
    /**
     * 获取除了自己以外的所有在线好友
     */
    public static List<String> getOnlineUser(String id) {
        List<String> users = Lists.newArrayList();
        userChannelMap.entrySet().forEach(item -> {
                    if (!item.getKey().equals(id) ) {
                        users.add(item.getKey());
                    }
                }
        );
        return users;
    }
    public static ConcurrentHashMap getChannelMap(){
        return userChannelMap;
    }
}
